package org.nyt.medicalstore.service.impl;

import org.nyt.medicalstore.model.Inventory;
import org.nyt.medicalstore.repository.InventoryRepository;
import org.nyt.medicalstore.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private InventoryRepository inventoryRepository;

    @Override
    public Inventory saveInventory(Inventory inventory) {
        return inventoryRepository.save(inventory);
    }

    @Override
    public Inventory getInventoryById(Long id) {
        Optional<Inventory> inventory = inventoryRepository.findById(id);
        return inventory.orElse(null);
    }

    @Override
    public List<Inventory> getAllInventories() {
        return inventoryRepository.findAll();
    }

    @Override
    public void deleteInventory(Long id) {
        inventoryRepository.deleteById(id);
    }

    @Override
    public List<Inventory> getLowStockDrugs() {
        return inventoryRepository.findLowStockDrugs();
    }

    @Override
    public List<Inventory> getExpiringDrugs() {
        return inventoryRepository.findByIsExpiringTrue();
    }

    @Override
    public List<Inventory> getExpiringDrugsByDays(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, days);
        Date warningDate = calendar.getTime();
        return inventoryRepository.findExpiringDrugs(warningDate);
    }

    @Override
    public Inventory updateQuantity(Long id, Integer quantity) {
        Optional<Inventory> inventoryOpt = inventoryRepository.findById(id);
        if (inventoryOpt.isPresent()) {
            Inventory inventory = inventoryOpt.get();
            inventory.setQuantity(quantity);
            inventory.setLastUpdated(new Date());
            return inventoryRepository.save(inventory);
        }
        return null;
    }

    @Override
    public Inventory updateMinQuantity(Long id, Integer minQuantity) {
        Optional<Inventory> inventoryOpt = inventoryRepository.findById(id);
        if (inventoryOpt.isPresent()) {
            Inventory inventory = inventoryOpt.get();
            inventory.setMinQuantity(minQuantity);
            inventory.setLastUpdated(new Date());
            return inventoryRepository.save(inventory);
        }
        return null;
    }

    @Override
    public Inventory updateExpiryWarningDays(Long id, Integer days) {
        Optional<Inventory> inventoryOpt = inventoryRepository.findById(id);
        if (inventoryOpt.isPresent()) {
            Inventory inventory = inventoryOpt.get();
            inventory.setExpiryWarningDays(days);
            inventory.setLastUpdated(new Date());
            return inventoryRepository.save(inventory);
        }
        return null;
    }
} 